package com.neo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Created by haowei on 2018/12/18.
 */
@Component
public class IOUtils {

    private static final Logger logger= LoggerFactory.getLogger(IOUtils.class);
    @Autowired
    private FileContentType fastContentType;

    /**
     * @param is
     * @param remoteFileName
     * @param response
     */
    public void download(InputStream is, String remoteFileName, HttpServletResponse response) {
        OutputStream os=null;
        try {
            if (response != null) {
                os = response.getOutputStream();
                String key= FileContentType.getFilenameSuffix(remoteFileName);
                String contentType = fastContentType.EXT_MAPS.get(key);
                //contentType="image/jpeg";
                // 设置响应头
                if (!StringUtils.isEmpty(contentType)) {
                    // 文件编码 处理文件名中的 '+'、' ' 特殊字符
                    String encoderName = URLEncoder.encode(remoteFileName, "UTF-8").replace("+", "%20").replace("%2B", "+");
                    response.setHeader("Content-Disposition", "attachment;filename=\"" + encoderName + "\"");
                    response.setContentType(contentType + ";charset=UTF-8");
                    response.setHeader("Accept-Ranges", "bytes");
                }
                byte[] buffer = new byte[1024 * 5];
                int len = 0;
                while ((len = is.read(buffer)) > 0) {
                    os.write(buffer, 0, len);
                }
                os.flush();
            }
        } catch (Exception e) {
            logger.error("download file failed", e);
        } finally {
            // 关闭流
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
